import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;


@WebServlet("/postjson")
public class JsonPostServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置返回类型和编码
        resp.setContentType("text/html; charset=utf-8");
        int length=req.getContentLength();

        // 1.得到数据流
        ServletInputStream inputStream = req.getInputStream();
        // 2.使用数组接收流信息
        byte[] bytes = new byte[length];
        inputStream.read(bytes);
        // 3.将数组转换成字符串（或对象）
        String result = new String(bytes, "utf-8");
        System.out.println(result);

        //4.字符串转换成对象(或字典)
        ObjectMapper objectMapper=new ObjectMapper();
        HashMap<String,String> map=objectMapper.readValue(result,HashMap.class);
        System.out.println("用户名:"+map.get("username"));
        System.out.println("密码:"+map.get("password"));
        resp.getWriter().println("用户名:"+map.get("username")+"|密码:"+map.get("password"));
    }
}
